<template>
  <div class="pop-dialog-container">
    <div class="pop-dialog-main">
      <el-form label-position="right" :model="facilityMaintenanceRecordForm" :label-width="formLabelWidth" ref="facilityMaintenanceRecordFormRef" :rules="rules">
        <el-row>
          <el-col :span="11">
            <el-form-item label="公共设施名称" prop="facilityName">
              <el-input v-model="facilityMaintenanceRecordForm.facilityName" placeholder="请选择公共设施名称" readonly="readonly">
                <template #suffix>
                  <el-icon @click="findFacility"><Search/></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="保养开始时间" prop="maintenanceStartDate">
              <el-date-picker
                  v-model="facilityMaintenanceRecordForm.maintenanceStartDate" type="date" placeholder="保养开始时间" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="保养开始时间" prop="maintenanceEndDate">
              <el-date-picker
                  v-model="facilityMaintenanceRecordForm.maintenanceEndDate" type="date" placeholder="保养开始时间" value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="维修保养人员" prop="staffName">
              <el-input v-model="facilityMaintenanceRecordForm.staffName" placeholder="请选择维修保养人员" readonly="readonly">
                <template #suffix>
                  <el-icon @click="findStaff"><Search/></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="facilityMaintenanceRecordForm.remark" placeholder="请输入备注" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="pop-dialog-footer">
      <el-row>
        <el-col :span="11" :offset="6">
          <div class="form-button-container">
            <el-button type="primary" @click="onSave">保存</el-button>
            <el-button @click="onReset">重置</el-button>
            <el-button type="primary" @click="onBack">关闭</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog v-model="facilitySelectorVisible" v-if="facilitySelectorVisible" title="公共设施信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <facility-selector @facility-selected-event="handleFacilitySelectedEvent">
      </facility-selector>
    </el-dialog>
    <el-dialog v-model="staffSelectorVisible" v-if="staffSelectorVisible" title="维修保养人员选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <staff-selector @staff-selected-event="handleStaffSelectedEvent">
      </staff-selector>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {defineEmits, defineProps, inject, onMounted, reactive, ref, toRefs} from 'vue';
import facilityMaintenanceRecordApi from '@/api/facilityMaintenanceRecordApi'
import type {FormInstance} from 'element-plus';
import {ElMessage} from 'element-plus'
import type {FacilityMaintenanceRecordForm} from "@/types/req/facilityMaintenanceRecordForm";
import type {Result} from '@/types/result'
import type {FacilityMaintenanceRecord} from "@/types/resp/facilityMaintenanceRecord";
import type {Id} from "@/types/id";
import { Search } from '@element-plus/icons-vue';
import FacilitySelector from "@/views/facility/FacilitySelector.vue";
import StaffSelector from "@/views/staff/StaffSelector.vue";

const props = defineProps<Id>()
const facilityMaintenanceRecordFormRef = ref<FormInstance | null>(null);
const facilityMaintenanceRecordForm = reactive<FacilityMaintenanceRecordForm>({
  facilityId: 0,
  facilityName: '',
  maintenanceStartDate: '',
  maintenanceEndDate: '',
  staffId: 0,
  staffName: '',
  remark: '',
})
const facilitySelectorVisible = ref<boolean>(false)
const staffSelectorVisible = ref<boolean>(false)
const emit = defineEmits<{
  (e: 'resetFacilityMaintenanceRecordAddEvent'): void;
  (e: 'closeFacilityMaintenanceRecordAddEvent', data?: { search: boolean }): void;
}>()

const rules = reactive({
  facilityName: [
    { required: true, message: '请输入公共设施名称', trigger: 'blur' }
  ],
});
const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')
const formLabelWidth = ref<string>('')

onMounted(() => {
  if (props.id) {
    initFacilityMaintenanceRecordFormById(props.id)
  }
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string, formLabelWidth?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.formLabelWidth) {
    formLabelWidth.value = globalStateRefs.formLabelWidth.value || ''
  }
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
});

const initFacilityMaintenanceRecordFormById = async (id: number) => {
  const resp: Result<FacilityMaintenanceRecord> = await facilityMaintenanceRecordApi.findById(id)
  if (resp && resp.code === 1 && resp.data) {
    Object.assign(facilityMaintenanceRecordForm, resp.data)
  }
}

const onReset = () => {
  if (facilityMaintenanceRecordFormRef.value) {
    facilityMaintenanceRecordFormRef.value.resetFields()
  }
  emit('resetFacilityMaintenanceRecordAddEvent')
}

const onSave = () => {
  if (!facilityMaintenanceRecordFormRef.value) {
    return
  }
  facilityMaintenanceRecordFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      const resp: Result<void> = await facilityMaintenanceRecordApi.save(facilityMaintenanceRecordForm)
      if (resp && resp.code === 1) {
        ElMessage.success('保存成功')
        emit('closeFacilityMaintenanceRecordAddEvent', {search: true})
      } else {
        ElMessage.error('保存失败:' + (resp.msg ? resp.msg : ''))
      }
    }
  })
}

const findFacility = () => {
  facilitySelectorVisible.value = true
}

const handleFacilitySelectedEvent = (selectedFacility: any) => {
  facilitySelectorVisible.value = false
  if (selectedFacility && 'facilityId' in selectedFacility && facilityMaintenanceRecordForm.facilityId !== selectedFacility['facilityId']) {
    facilityMaintenanceRecordForm.facilityId = selectedFacility['facilityId']
    facilityMaintenanceRecordForm.facilityName = selectedFacility['facilityName']
  }
}

const findStaff = () => {
  staffSelectorVisible.value = true
}

const handleStaffSelectedEvent = (selectedStaff: any) => {
  staffSelectorVisible.value = false
  if (selectedStaff && 'staffId' in selectedStaff && facilityMaintenanceRecordForm.staffId !== selectedStaff['staffId']) {
    facilityMaintenanceRecordForm.staffId = selectedStaff['staffId']
    facilityMaintenanceRecordForm.staffName = selectedStaff['staffName']
  }
}

const onBack = () => {
  emit('closeFacilityMaintenanceRecordAddEvent')
}
</script>

<style lang="scss">
</style>
